<?php

class UserDAO {
    
    public static function login($login, $password) {
        $db = Database::getInstance();
        $db->query("SELECT salt FROM users WHERE login like '" . $login . "'");
        if($db->getNumRows() < 1) {
            return 0;
        }
        $salt = $db->getOne();
        //var_dump($salt);
        $password = UserDAO::password($password, $salt);
        //var_dump($password);
        $db->query("SELECT uid FROM users WHERE login like '" . $login . "' AND password like '" . $password . "'");
        if($db->getNumRows() == 1) {
            $uid = $db->getOne();
            $db->query("UPDATE users SET last_login=NOW() where login like '" . $login . "'");
            return $uid;
        }
        else {
            return 0;
        }
    }
    
    public static function getUserInfo($uid) {
        $db = Database::getInstance();
        $db->query("SELECT * FROM users WHERE uid = " . (int)$uid);
        if($db->getNumRows() > 0) {
            return array_merge(
                    $db->dbToObjectKeys($db->getRowAssoc()),
                    array("rights"=>UserDAO::getRights($uid))
                   );
        }
        else {
            return array();
        }
    }
    public static function password($password, $salt) {
        if(strlen($password) > 10) {
            $password = substr($password,0,10);
        }
        else {
            $password = str_pad($password,10);
        }
        $password = $salt . substr($password,0,5) . $salt . substr($password,5) . $salt;
        $password = sha1($password);
        return $password;
    }
    
    public static function getRights($uid, $userOnly = false) {
        $db = Database::getInstance();
        $gRights = array();
        if(!$userOnly) {
            $db->query("
                        SELECT
                            g.mid, g.lvl
                        FROM
                                group_rights g
                            JOIN
                                users u
                            ON(g.gid = u.gid)
                        WHERE
                            u.uid = " . (int)$uid);

            $gRights = $db->getObjectArray();
        }
        $db->query("SELECT mid,lvl FROM user_rights WHERE uid = " . $uid);
        $uRights = $db->getObjectArray();
        $rights = array();
        if(count($gRights)) {
            foreach($gRights as $key => $right) {
                $rights[$right->mid] = $right->lvl;
            }
        }
        if(count($uRights)) {
            foreach($uRights as $key => $right) {
                    $rights[$right->mid] = $right->lvl;
            }
        }
        return $rights;
    }
    
    public static function createUser($user) {
        if(!UserDAO::checkUser($user,true)) {
            return false;
        }

        $db = Database::getInstance();
        $salt = rand(10,99);
        $user->setPassword(UserDAO::password($user->getPassword(), $salt));
        $db->query("INSERT INTO users(name,surname,login,password,salt,gid,enabled) VALUES(
            '" . $user->getName() . "',
            '" . $user->getSurname() . "',
            '" . $user->getLogin() . "',
            '" . $user->getPassword() . "',
            '" . $salt . "',
            " . $user->getGid() . ",
            " . $user->getEnabled() . "
            )");
        echo mysql_error();
        return $db->insertId();
    }
    
    public static function deleteUser($user) {
        if($user->getUid() < 1) {
            return false;
        }
        $db = Database::getInstance();
        $db->query("DELETE FROM adjustments WHERE uid=" . $user->getUid());
        $db->query("DELETE FROM users WHERE uid=" . $user->getUid());
        $db->query("DELETE FROM project_tasks_to_users WHERE uid=" . $user->getUid());
        $db->query("DELETE FROM user_money_info WHERE uid=" . $user->getUid());
        $db->query("DELETE FROM user_rights WHERE uid=" . $user->getUid());
        $db->query("DELETE FROM works WHERE uid=" . $user->getUid());
        $db->query("DELETE FROM work_trips WHERE uid=" . $user->getUid());
        return true;
    }
    
    public static function checkUser($user, $checkPass) {
        $err = Error::instance();
        $cnt = $err->count();
        $db = Database::getInstance();
        if(strlen($user->getLogin()) < 5) {
            $err->add("Login musi mieć minimum 5 znaków.");
        }
        if($checkPass) {
            if(strlen($user->getPassword()) < 8) {
                $err->add("Hasło musi mieć minimum 8 znaków.");
            }
        }
        
        if($user->getGid() < 1) {
            $err->add("Nie wybrano grupy dla użytkownika.");
        }
        
        if(strlen($user->getName()) < 1) {
            $err->add("Nie podano imienia.");
        }

        if(strlen($user->getSurname()) < 1) {
            $err->add("Nie podano nazwiska.");
        }
        
        $db->query("SELECT uid FROM users WHERE login LIKE '" . $user->getLogin() . "'" . ($user->getUid() > 0 ? " AND uid!=" . $user->getUid() : ''));
        if($db->getNumRows() > 0) {
            $err->add("Użytkownik o podanym loginie istnieje już w bazie.");
        }
        if($err->count() > $cnt) {
            return false;
        } else {
            return true;
        }
    }
    
    public static function updateUserInfo($user) {
        if(!UserDAO::checkUser($user,strlen($user->getPassword())>0)) {
            return false;
        }
        $db = Database::getInstance();
        if(strlen($user->getPassword()) > 0) {
            $db->query("SELECT salt FROM users WHERE uid=" . $user->getUid());
            $salt = $db->getOne();
        }       
        $db->query("
            UPDATE
                users
            SET
                name='" . $user->getName() . "',
                surname='" . $user->getSurname() . "',
                login='" . $user->getLogin() . "',
                enabled=" . (int)$user->getEnabled() . ",
                gid=" . (int)$user->getGid() .
                (strlen($user->getPassword()) > 0 ? ", password='" . UserDAO::password($user->getPassword(),$salt) . "'" : '') . "
            WHERE
                uid=" . $user->getUid());
        return true;
    }
    
    public static function getRates($user) {
        $db = Database::getInstance();
        $db->query("SELECT normal_rate, overhours_rate, weekend_rate, trip_rate FROM user_money_info WHERE uid=" . $user->getUid());
        if($db->getNumRows() > 0) {
            return $db->getRowObject();
        } else {
            $std = new stdClass();
            $std->normal_rate = 0;
            $std->overhours_rate = 0;
            $std->weekend_rate = 0;
            $std->trip_rate = 0;
            return $std;
        }
    }
    
    public static function setRates($user, $rates) {
        $db = Database::getInstance();
        $db->query("SELECT * FROM user_money_info WHERE uid=" . $user->getUid());
        if($db->getNumRows() > 0) {
            $db->query("UPDATE
                            user_money_info
                        SET
                            normal_rate=" . $rates->normal_rate . ", 
                            overhours_rate=" . $rates->overhours_rate . ", 
                            weekend_rate=" . $rates->weekend_rate . ", 
                            trip_rate=" . $rates->trip_rate . "
                        WHERE
                            uid=" . $user->getUid()
                    );
        } else {
            $db->query("INSERT INTO
                                user_money_info(uid,normal_rate, overhours_rate, weekend_rate, trip_rate, hours_weekly) VALUES(
                                " . $user->getUid() . ",
                                " . $rates->normal_rate . ",
                                " . $rates->overhours_rate . ",
                                " . $rates->weekend_rate . ",
                                " . $rates->trip_rate . ",
                                0)
                        ");
        }
        return $db->getAffectedRows() > 0;
    }
    
    public static function getHoursWeekly($user) {
        $db = Database::getInstance();
        $db->query("SELECT hours_weekly FROM user_money_info WHERE uid=" . $user->getUid());
        if($db->getNumRows() > 0) {
            return $db->getOne();
        } else {
            return 0;
        }
    }
    
    public static function setHoursWeekly($user, $hours) {
        $db = Database::getInstance();
        $db->query("SELECT * FROM user_money_info WHERE uid=" . $user->getUid());
        if($db->getNumRows() > 0) {
            $db->query("UPDATE
                            user_money_info
                        SET
                            hours_weekly=$hours
                        WHERE
                            uid=" . $user->getUid()
                    );
        } else {
            $db->query("INSERT INTO
                                user_money_info(uid, normal_rate, overhours_rate, weekend_rate, trip_rate, hours_weekly) VALUES(
                                " . $user->getUid() . ",
                                0,
                                0,
                                0,
                                0,
                                $hours)
                        ");
        }
        return $db->getAffectedRows() > 0;
    }
    
    public static function getAdjustment($user) {
        $db = Database::getInstance();
        $db->query("SELECT value,comment FROM adjustments WHERE MONTH(`date`) = MONTH('" . date('Y-m-d') . "') AND YEAR(`date`) = YEAR('" . date('Y-m-d') . "') AND uid=" . $user->getUid());
        if($db->getNumRows() > 0) {
            return $db->getRowAssoc();
        } else {
            return array('value'=>0,'comment'=>'');
        }
            
    }
}

?>